// pages/chat/interaction/interaction.js
var app = getApp();
const qiniuUploader = require("../../../utils/qiniuUploader");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    objID: null,
    inputValue: "",
    chatItem: [],
    obj: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    app.createDefaultUser(options.id);
    this.setData({
      "objID": options.id,
      "chatItem": app.globalData.history[options.id]["message"]
    });

    if (options.nickname !== undefined){
      wx.setNavigationBarTitle({
        title: options.nickname
      });
    }else{
      app.refreshUserInfo(function(){
        var title = app.globalData.history[options.id]["user"]["nick_name"];
        wx.setNavigationBarTitle({
          title: title
        });
      })
    }
    
    wx.getUserInfo({
      success: function(res){
        var avatarUrl = res.userInfo.avatarUrl;
        that.setData({
          "selfAvatar": avatarUrl
        })
      }
    })

    app.registerMessage(options.id, function(msg){
      app.globalData["history"][options.id]["new"] = false;
      that.showMsg({
        obj: true,
        text: msg["text"],
        "type": msg["type"]
      })
    });
    that.pageScrollToBottom();
  },

  onSendInput: function(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  onSendTap: function(e){
    var input = this.data.inputValue;
    if(input === ""){
      return;
    }

    this.showMsg({
      obj: false,
      text: input,
      "type": "text"
    });

    this.setData({
      inputValue: "",
    });
    app.sendTo(this.data.objID, input, "text");
  },

  showMsg: function(msg){
    var chatItem = this.data.chatItem;
    chatItem.push(msg)
    this.setData({
      chatItem: chatItem,
    });
    this.pageScrollToBottom();
  },

  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload: function () {
    app.unregisterMessage(this.data.objID);
  },

  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#body').boundingClientRect(function (rect) {
      console.log(rect);
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.height
      })
    }).exec()
  },


  onSendImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePath = res.tempFilePaths[0];
        wx.showModal({
          title: '发送图片',
          content: '确认要发送这张图片吗？',
          success: ()=>{
            wx.showLoading({
              title: '正在上传中',
              mask: true
            })
            qiniuUploader.upload(tempFilePath, (res) => {
              var url = "http://" + res.imageURL;
              app.sendTo(that.data.objID, url, "image");

              that.showMsg({
                obj: false,
                text: url,
                "type": "image"
              })
              wx.hideLoading()
            }, (error) => {
              console.log('error: ' + error);
            }, {
                region: 'ECN',
                domain: 'p7j8cql4g.bkt.clouddn.com',
                uptokenURL: "https://bookin.moha.vip/uptoken/",
                shouldUseQiniuFileName: true
              }, (res) => {
                console.log(res)
              });
          }
        })
        
      }
    })
  },

  previewChatImage: function(e){
    var url = e.target.dataset["url"];
    wx.previewImage({
      urls: [url],
    })
  },

  openBook: function(e){
    var id = e.currentTarget.dataset["bid"];
    console.log(e);
    wx.navigateTo({
      url: '/pages/bookDetail/bookDetail?id=' + id,
    })
  }
})